package net.mysoft.framework.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;

import bsh.EvalError;
import bsh.Interpreter;

public class BshUtils {
	private static Logger logger = Logger.getLogger(BshUtils.class);

	private Interpreter bsh = null;

	public BshUtils() {
		bsh = new Interpreter();
	}

	public Interpreter getBsh() {
		return bsh;
	}

	public final Object eval(String expr, Map varMap) throws Exception {
		Object obj = null;
		if (varMap == null || null == expr || "".equals(expr)) {
			return null;
		}

		Iterator it = varMap.keySet().iterator();
		try {
			while (it.hasNext()) {
				String key = (String) it.next();
				Object value = varMap.get(key);
				setValue(key, value);
			}
			obj = bsh.eval(expr);

			// 返回变量
			return obj;
		} catch (Exception ex) {
			logger.error(ex);
			throw ex;
		}
	}

	public Object eval(String expr){
		Object obj = null;
		try {
			obj = bsh.eval(expr);
		} catch (Exception e) {
			logger.error(ExceptionUtil.getExceptionMessage(e));
		}
		return obj;
	}
	
	// 变量赋值
	private void setValue(String key, Object value) throws EvalError {
		if (value instanceof Boolean) {
			bsh.set(key, ((Boolean) value).booleanValue());
		} else if (value instanceof Byte) {
			bsh.set(key, ((Byte) value).byteValue());
		} else if (value instanceof Character) {
			bsh.set(key, ((Character) value).charValue());
		} else if (value instanceof Short) {
			bsh.set(key, ((Short) value).shortValue());
		} else if (value instanceof Integer) {
			bsh.set(key, ((Integer) value).intValue());
		} else if (value instanceof Long) {
			bsh.set(key, ((Long) value).longValue());
		} else if (value instanceof Float) {
			bsh.set(key, ((Float) value).floatValue());
		} else if (value instanceof Double) {
			bsh.set(key, ((Double) value).doubleValue());
		} else {
			bsh.set(key, value);
		}
	}
	
	 public static void main(String[] args) {  
		  
	        BshUtils bsh = new BshUtils();  
	        String expr = "a==1&&b.equals(\"c\")";  
	        String expr2 = "a+c";  
	        Map<String, Object> map = new HashMap<String, Object>();  
	        map.put("a", 1);  
	        map.put("b", "c");  
	        map.put("c", 2);  
	        try {  
	            System.out.println("--------expr--------------> "  
	                    + bsh.eval(expr, map).toString());  
	            System.out.println("--------expr2--------------> "  
	                    + bsh.eval(expr2, map).toString());  
	            System.out.println("--------expr3--------------> "  
	                    + bsh.eval("0<=0 && 0+0<=0").toString());  
	        } catch (Exception e) {  
	            // TODO Auto-generated catch block  
	            e.printStackTrace();  
	        }  
	  
	    }  
}
